package com.LeetCode.Search;

import org.junit.Test;

/**
 * 岛屿数量
 */
public class CountOfLand {
    public int numIslands(char[][] grid) {
        if(grid.length == 0 || grid[0].length == 0) return 0;
        int res = 0;
        int n = grid.length;
        int m = grid[0].length;
        for(int i = 0; i<n; i++){
            for(int j = 0; j<m; j++){
                if(grid[i][j] == '1'){
                    dfs(grid, i , j);
                    res++;
                }
            }
        }
        return res;
    }

    //记录搜索到哪里
    public void dfs(char[][] grid , int i, int j){
        if(i < 0 || i >= grid.length ||
            j < 0 || j >= grid[0].length || grid[i][j] == '0') return;
        grid[i][j] = '0';
        dfs(grid, i+1, j);
        dfs(grid, i-1, j);
        dfs(grid, i, j+1);
        dfs(grid, i, j-1);
    }


    @Test
    public void testNumIslands(){
        char[][] lands = {
                {'1','1','1','1','0'},
                {'1','1','0','1','0'},
                {'1','1','0','0','1'},
                {'0','0','0','1','1'}
        };

        System.out.println(numIslands(lands));
    }
}
